//
//  ClassifyTwoViewController.m
//  MoGuRadio
//
//  Created by 李响 on 15/6/12.
//  Copyright (c) 2015年 mogu.com 蘑菇科技. All rights reserved.
//

#import "ClassifyTwoViewController.h"
#import "AFNetworking.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"
#import "Table.h"
#import "TableViewOneCell.h"
#import "MBProgressHUD.h"
#import "SpecialPageViewController.h"
#import "MyRadioViewController.h"
@interface ClassifyTwoViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *tempArr;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) NSMutableArray *sourceArr;

@property (nonatomic, assign) NSInteger num;
@property (nonatomic, retain) NSString *str;
@property (nonatomic, retain) NSString * str2;
@property (nonatomic, retain) NSString * str3;
@property (nonatomic, retain) NSString * str4;

@property (nonatomic, retain)NSMutableArray * lastArraytT;
@property (nonatomic, retain)NSMutableArray * lastArraytM;
@property (nonatomic, retain)NSMutableArray * lastArraytN;

@end
@implementation ClassifyTwoViewController
- (void)dealloc
{
    [_tableView release];
    [_tempArr release];
    [_keBian release];
    [_keBian2 release];
    
    [_sourceArr release];
    [_lastArraytT release];
    [_lastArraytM release];
    [_lastArraytN release];
    
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.sourceArr =[NSMutableArray array];
        self.tempArr = [NSMutableArray array];
        
        self.lastArraytT = [NSMutableArray array];
        self.lastArraytM = [NSMutableArray array];
        self.lastArraytN = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height / 13)];
    //view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.945 alpha:1.0];
    view.backgroundColor = [UIColor whiteColor];
    view.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:view];
    [view release];
    
    //分段控制器
    UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:@[@"最新", @"最热"]];
    seg.frame = CGRectMake(self.view.bounds.size.width * 4 / 7, 0+2, self.view.bounds.size.width * 2 / 5, self.view.bounds.size.height / 13-10);
    [seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:seg];
    
    //在创建seg的时候.可以设置默认选中某一个分段
    seg.selectedSegmentIndex = 1;
    //设置seg颜色
    seg.tintColor = [UIColor colorWithRed:0.97 green:0.59 blue:0.80 alpha:1.0];
    [self analysis];
    [self setUpTableView];
    [seg release];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width * 4 / 7, self.view.bounds.size.height / 13 - 5)];
    imageView.image = [UIImage imageNamed:@"lxlx.png"];
    [view addSubview:imageView];
    [imageView release];
    UIImageView *imageViewB = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height / 13 - 5, self.view.bounds.size.width, self.view.bounds.size.height / 35)];
    imageViewB.image = [UIImage imageNamed:@"lxxm.png"];
    [view addSubview:imageViewB];
    [imageViewB release];
    
    UIImage *image = [UIImage imageNamed:@"tuihui@2x.png"];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(leftbuttonAction)] autorelease];
}
- (void)leftbuttonAction
{
    // 在这里增加返回按钮的自定义动作
    [self.navigationController popViewControllerAnimated:YES];
}

#warning 随机颜色用法
/*
 - (UIColor *)getRandomColor
 {
 UIColor *color = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
 return color;
 }
 */
- (void)segAction:(UISegmentedControl *)seg
{
    //判断seg的下标
    if (seg.selectedSegmentIndex == 0) {
        //VALID_START_DATE_DESC//HOT_RANK_DESC
        //最新
        self.keBian2 = @"VALID_START_DATE_DESC";
        
    } else {
        self.keBian2 = @"HOT_RANK_DESC";
    }
    self.str = [NSString stringWithFormat:@"http://api.kaolafm.com/api/v3.1/resource/search?words=&cid=%@&sorttype=%@&pagesize=10&pagenum=1&installid=0000TLD3&udid=eca85b7ac579ac2b4a4f9fec6744f8fd&sessionid=eca85b7ac579ac2b4a4f9fec6744f8fd1434179097505&imsi=460036090834220&operator=3&network=1&timestamp=1434179122&playid=1612f6b0e58128cf346cdec7a26da4ad&sign=f3e82c19c896a40926481f50f62d2a8c&appid=0&channel=A-baidu&version=3.6.1&devicetype=0&resolution=480*854&", self.keBian , self.keBian2];
    
    self.str = [_str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manger GET:_str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [responseObject objectForKey:@"result"];
        self.tempArr = [dic objectForKey:@"dataList"];
        [self.tableView headerEndRefreshing];
        [self shuZu];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }];
}
//默认的
- (void)analysis
{
    NSString *str = [NSString stringWithFormat:@"http://api.kaolafm.com/api/v3.1/resource/search?words=&cid=%@&sorttype=HOT_RANK_DESC&pagesize=10&pagenum=%ld&installid=0000TLD3&udid=eca85b7ac579ac2b4a4f9fec6744f8fd&sessionid=eca85b7ac579ac2b4a4f9fec6744f8fd1434076407356&imsi=460036090834220&operator=3&network=1&timestamp=1434076599&playid=e5eaf8bead36e52d4b331f3266a11d48&sign=f3e82c19c896a40926481f50f62d2a8c&appid=0&channel=A-baidu&version=3.6.1&devicetype=0&resolution=480*854&", self.keBian, (long)self.num];
    
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manger GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [responseObject objectForKey:@"result"];
        self.tempArr = [dic objectForKey:@"dataList"];
        
        [self.tableView headerEndRefreshing];
        [self shuZu];
        for (NSMutableDictionary *temyDic in _tempArr) {
            self.str4 =  [temyDic objectForKey:@"pic"];
            [self.lastArraytT addObject:self.str4];
        }
        for (NSMutableDictionary *tempDic in _tempArr) {
            self.str2 = [[[[tempDic objectForKey:@"audioList"] firstObject] objectForKey:@"audioInfo"] objectForKey:@"audioName"];
            self.str3 = [[[[tempDic objectForKey:@"audioList"] firstObject] objectForKey:@"audioInfo"] objectForKey:@"mp3PlayUrl"];
            [self.lastArraytN addObject:self.str2];
            [self.lastArraytM addObject:self.str3];
        }
        //        for (NSMutableDictionary *dic in self.tempArr) {
        //            [self.mainArr addObject:dic];
        //            [self.tableView reloadData];
        //        }
        
        //        self.tableView.frame = CGRectMake(0, 64+(self.view.bounds.size.height / 13), VIEW_WIDTH, (self.view.bounds.size.height / 8) * self.mainArr.count);
        //        self.num +=1;
        //        [self.tableView footerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }];
}
- (void)shuZu
{
    self.sourceArr = [Table mainArrWithDicArr:self.tempArr];
    [self.tableView reloadData];
}
- (void)setUpTableView
{
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height / 13, self.view.bounds.size.width, self.view.bounds.size.height - (self.view.bounds.size.height / 13 + 64 + 49))style:UITableViewStylePlain];
    //    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    [self.tableView addHeaderWithTarget:self action:@selector(analysis)];
    [self.tableView headerBeginRefreshing];
//    [self.tableView addFooterWithTarget:self action:@selector(analysis)];
//    [self.tableView footerBeginRefreshing];
    
    [self.tableView registerClass:[TableViewOneCell class] forCellReuseIdentifier:@"diyi"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableViewOneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"diyi"];
    Table *main = [self.sourceArr  objectAtIndex:indexPath.row];
    cell.main = main;
    [cell sendint:indexPath.row];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [cell.playImageView addGestureRecognizer:tap];
    [tap release];
    return cell;
}
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    MyRadioViewController *myRadioVC = [MyRadioViewController shareInstance];
    
    NSString *strN = [self.lastArraytN objectAtIndex:tap.view.tag];
    NSString *strT = [self.lastArraytT objectAtIndex:tap.view.tag];
    NSString *strM = [self.lastArraytM objectAtIndex:tap.view.tag];
    myRadioVC.rname = strN;
    myRadioVC.mp3Url = strM;
    myRadioVC.playImage = strT;
    //myRadioVC.mp3Url = [NSString stringWithFormat:@"%@", self.str2];
    [self.navigationController pushViewController:myRadioVC animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.sourceArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.bounds.size.height / 7;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    Table *teble = [self.sourceArr objectAtIndex:indexPath.row];
    SpecialPageViewController *specialVC = [[SpecialPageViewController alloc] init];
    specialVC.rid = [[[self.tempArr objectAtIndex:indexPath.item] objectForKey:@"rid"] description];
    specialVC.pic = [[self.tempArr objectAtIndex:indexPath.item] objectForKey:@"pic"];
    specialVC.hostName = [[[[self.tempArr objectAtIndex:indexPath.item] objectForKey:@"host"] firstObject] objectForKey:@"name"];
    specialVC.foucsNum = [[self.tempArr objectAtIndex:indexPath.item] objectForKey:@"followedNum"];
    specialVC.listenNum = [[self.tempArr objectAtIndex:indexPath.item] objectForKey:@"listenNum"];
    specialVC.descRadio = [[self.tempArr objectAtIndex:indexPath.item] objectForKey:@"radioDesc"];
    specialVC.titleLabel = [[self.tempArr objectAtIndex:indexPath.item] objectForKey:@"rname"];
    [self.navigationController pushViewController:specialVC animated:YES];
    [specialVC release];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
